package org.keshproject.dms.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.keshproject.dms.pojo.BalanceSheet;
import org.keshproject.dms.service.ICompanyService;
import org.keshproject.dms.service.IFinanceService;
import org.keshproject.dms.util.ExcelReportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

@Namespace("/finance")
@Controller
public class FinanceAction extends ActionSupport {

	@Autowired
	public IFinanceService financeService;

	@Autowired
	public ICompanyService companyService;

	private InputStream fileInputStream;
	private String excelName;

	@Action(value = "/index", results = { @Result(name = "success", location = "/finance.jsp", type = "redirect") })
	public String execute() {
		return SUCCESS;
	}

	@Action(value = "/download", results = { @Result(name = "success", type = "stream", params = {
			"contentType", "application/vnd.ms-excel", "inputName",
			"fileInputStream", "contentDisposition",
			"filename=\"${excelName}\"", "bufferSize", "1024" }) })
	public String input() {
		this.setExcelName("FinanceReport.xls");
		return SUCCESS;
	}

	public InputStream getFileInputStream() {
		BalanceSheet bs2008 = financeService.getBalanceSheet(1, 2008);
		BalanceSheet bs2009 = financeService.getBalanceSheet(1, 2009);

		HSSFWorkbook wb = ExcelReportUtil.getFinanceReport(bs2008, bs2009);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			wb.write(baos);
		} catch (IOException e) {
			this.addActionError("Download Failed");
			e.printStackTrace();
		}
		byte[] ba = baos.toByteArray();
		ByteArrayInputStream bais = new ByteArrayInputStream(ba);
		return bais;
	}

	public void setFileInputStream(InputStream fileInputStream) {
		this.fileInputStream = fileInputStream;
	}

	public IFinanceService getFinanceService() {
		return financeService;
	}

	public void setFinanceService(IFinanceService financeService) {
		this.financeService = financeService;
	}

	public ICompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(ICompanyService companyService) {
		this.companyService = companyService;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

}
